﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TIBCO.EMS;
using System.Threading;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;
namespace TibcoMessageAdmin
{
    public partial class BrowserUI : Form

    {
        XmlDocument _xd = new XmlDocument();
        Hashtable ht = new Hashtable();
        List<Queue> queueList = new List<Queue>();
        string _messageID = "";
        public BrowserUI()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Util.LoadQueues(cboStoredQueues,ref queueList );
        }

        private void cmdShow_Click(object sender, EventArgs e)
        {

            ConnectionFactory factory = null;
            Connection connection = null;
            Session session = null;
            TIBCO.EMS.Queue queue = null;

            try
            {

                this.Text = string.Format("EMS Brower [Queue: {0}]", txtQueue.Text);
                listBox1.Items.Clear();
                factory = new TIBCO.EMS.ConnectionFactory(txtServer.Text);
                connection = factory.CreateConnection(txtUser.Text, txtPwd.Text);
                session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE);
                queue = session.CreateQueue(txtQueue.Text);


                connection.Start();
                QueueBrowser browser = session.CreateBrowser(queue);
                IEnumerator msgs = browser.GetEnumerator();
                TIBCO.EMS.TextMessage message;

                while (msgs.MoveNext())
                {
                    message = (TIBCO.EMS.TextMessage)msgs.Current;
                    TIBCO.EMS.Message ms1 = (TIBCO.EMS.Message)msgs.Current;                    
                    CustMsg cmg = new CustMsg(message);
                    listBox1.Items.Add(cmg);
                }


            }
            catch (EMSException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
            finally
            {
                // close the connection
                if (connection != null)
                {
                    connection.Close();
                }                
                factory = null;
                if (session != null)
                {
                    session.Close();
                }
                queue = null;
                

            }
        }


        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Visible = false;
                xmlBrowser1.Visible = true;
                CustMsg msg = (CustMsg)listBox1.SelectedItem;                
                _messageID = msg.MessageID;
                _xd.LoadXml(msg._txtMessage.Text);
                xmlBrowser1.XmlDocument = _xd;               
            }
            catch (Exception ex)
            {
                
                richTextBox1.Visible = true;
                xmlBrowser1.Visible = false;
                if (listBox1.SelectedItem != null)
                {
                    richTextBox1.Text = ((CustMsg)listBox1.SelectedItem)._txtMessage.Text ;
                }

            }

        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            bool browserNull = false;
            bool textNull = false;

            browserNull = (xmlBrowser1.XmlDocument == null ? true : false);
            textNull = (richTextBox1.Text.Trim().Length == 0 ? true : false);
            if (browserNull && textNull)
            {
                MessageBox.Show("Nothing to Save", "Info", MessageBoxButtons.OK);
                return;
            }


            saveFileDialog1.Filter = "XML File(*.xml)|*.xml|Text File(*.txt)|*.txt"; 
            saveFileDialog1.ShowDialog();

          

            try
            {
                if (!string.IsNullOrEmpty(saveFileDialog1.FileName))
                {
                    if (xmlBrowser1.Visible)
                    {
                        xmlBrowser1.XmlDocument.Save(saveFileDialog1.FileName);
                    }
                    else
                    {
                        File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);

            }
                
        }

        private void cmdEdit_Click(object sender, EventArgs e)
        {
            bool browserNull = false;
            bool textNull = false;

            browserNull = (xmlBrowser1.XmlDocument == null ? true : false);
            textNull = (richTextBox1.Text.Trim().Length == 0 ? true : false);
            if (browserNull && textNull)
            {
                MessageBox.Show("Nothing to Edit", "Info", MessageBoxButtons.OK);
                return;
            }


            try
            {
                frmEdit edit = new frmEdit();
                edit.MdiParent = this.ParentForm;

                if (xmlBrowser1.Visible && !string.IsNullOrEmpty(_xd.OuterXml))
                {
                    XDocument xDoc = XDocument.Parse(_xd.OuterXml);
                    edit.xml = xDoc.ToString(SaveOptions.None);
                    xDoc = null;
                }
                else
                {
                    edit.xml = richTextBox1.Text;

                }
                edit.FormClosed += new FormClosedEventHandler(edit_FormClosed);
                edit.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }                                   

        }

        void edit_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmEdit edit = (frmEdit)sender;

            try
            {

                    if (xmlBrowser1.Visible && !string.IsNullOrEmpty(edit.xml) )
                    {
                        _xd.LoadXml(edit.xml);
                        xmlBrowser1.XmlDocument = _xd;
                        xmlBrowser1.BringToFront();
                        xmlBrowser1.XmlText = edit.xml;
                    }
                    else
                    {
                        richTextBox1.Text = edit.xml;
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }              

        }

    


        private void button1_Click(object sender, EventArgs e)
        {
            TIBCO.EMS.Message msg = null;

            ConnectionFactory factory =null;
            Connection connection = null;
            Session session = null;
            TIBCO.EMS.Queue destination = null;
            MessageConsumer msgConsumer = null;
            try
            {
                factory = new TIBCO.EMS.ConnectionFactory(txtServer.Text);

                // create the connection
                connection = factory.CreateConnection(txtUser.Text, txtPwd.Text);

                // create the session
                session = connection.CreateSession(false, Session.AUTO_ACKNOWLEDGE);

                // set the exception listener
                //connection.ExceptionListener = this;

                // create the destination
                destination = session.CreateQueue(txtQueue.Text);

                // create the consumer
                msgConsumer = session.CreateConsumer(destination);

                // start the connection
                connection.Start();

                // read messages
                while (true)
                {
                    // receive the message with 50 ms timeout
                    msg = msgConsumer.Receive(50);
                    if (msg == null)
                        break;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);

            }
            finally
            {         
                // close the connection
                if (connection != null)
                {
                    connection.Close();
                }
                destination = null;
                factory = null;
                msgConsumer.Close();
            }

        }


        private void cmdSend_Click(object sender, EventArgs e)
        {
            bool browserNull = false;
            bool textNull = false;

            browserNull = (_xd.InnerXml == null ? true : false);
            textNull = (richTextBox1.Text.Trim().Length == 0 ? true : false);
            if (browserNull && textNull)
            {
                MessageBox.Show("Nothing to send", "Info", MessageBoxButtons.OK);
                return;
            }


            frmResend edit = new frmResend();

            edit.txtPwd.Text  = this.txtPwd.Text ;
            edit.txtQueue.Text = this.txtQueue.Text;
            edit.txtServer.Text = this.txtServer.Text;
            edit.txtUser.Text = this.txtUser.Text;

            try
            {
                if (xmlBrowser1.Visible && !string.IsNullOrEmpty(_xd.OuterXml))
                {
                    edit.XmlMessage = _xd.OuterXml;
                }
                else
                {
                    edit.XmlMessage = richTextBox1.Text;
                }
                edit.MessageID = _messageID;
                edit.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.DefaultExt = "*.*"; 
            openFileDialog1.ShowDialog();
            string fileame ="";
            
            

            try
            {
                if (!string.IsNullOrEmpty(openFileDialog1.FileName))
                {
                    fileame = openFileDialog1.FileName;
                    richTextBox1.Visible = false;
                    xmlBrowser1.Visible = true;



                    XmlDocument doc = new XmlDocument();


                    try
                    {
                        doc.Load(fileame);
                        _xd = doc;
                        xmlBrowser1.BringToFront();
                        xmlBrowser1.Navigate(fileame);

                    }
                    catch (Exception ex)
                    {
                        xmlBrowser1.Visible = false;
                        richTextBox1.Visible = true ;
                        richTextBox1.Text = GetFileContent(fileame);                                                

                    }  
                }
                else
                {
                    MessageBox.Show("No file selected to load", "Error", MessageBoxButtons.OK);

                }

            }
         
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
           

            
        }

        private string GetFileContent(string fileName)
        {
            StreamReader rdr =null;
            string txt = "";
            try
            {
                rdr = File.OpenText(fileName);
                txt = rdr.ReadToEnd();
                
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
            finally
            {
                rdr.Close();
            }
            return txt;

        }


        private void BrowserUI_Resize(object sender, EventArgs e)
        {

            richTextBox1.Width = this.Width - 140;
            xmlBrowser1.Width = this.Width - 140;
            listBox1.Width = this.Width - 140;
            richTextBox1.Height = this.Height - 415;
            xmlBrowser1.Height = this.Height - 415;
            panel1.Top = this.Height - 120;            



        }

        private void cmdSave_MouseMove(object sender, MouseEventArgs e)
        {            
            statusStrip1.Items[0].Text = "Please click to save the above displayed message to a file locally";
        }

        private void cmdSave_MouseLeave(object sender, EventArgs e)
        {
            statusStrip1.Items[0].Text = "";
        }

        private void cmdEdit_MouseMove(object sender, MouseEventArgs e)
        {
            statusStrip1.Items[0].Text = "Please click to edit the above displayed message. You can save it or send it to queue after editing ";
        }

        private void cmdEdit_MouseLeave(object sender, EventArgs e)
        {
            statusStrip1.Items[0].Text = "";
        }

        private void button2_MouseMove(object sender, MouseEventArgs e)
        {
            statusStrip1.Items[0].Text = "Please click to load a message from a file. You can save it or send it to queue after loading ";
        }

        private void button2_MouseLeave(object sender, EventArgs e)
        {
            statusStrip1.Items[0].Text = "";
        }

        private void cmdSend_MouseMove(object sender, MouseEventArgs e)
        {
            statusStrip1.Items[0].Text = "Send the currently displayed message to a queue";

        }

        private void cmdSend_MouseLeave(object sender, EventArgs e)
        {
            statusStrip1.Items[0].Text = "";
        }

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {



            if (xmlBrowser1.Visible && !string.IsNullOrEmpty(_xd.OuterXml))
            {
                xPath path = new xPath();
                path.MdiParent = this.ParentForm;

                XDocument xDoc = XDocument.Parse(_xd.OuterXml);
                path.xml = xDoc.ToString(SaveOptions.None);
                xDoc = null;
                path.Show();
            }
            else
            {
                MessageBox.Show("No xml is loaded to show xpath","Error",MessageBoxButtons.OK);                
            }


        }

        private void cboStoredQueues_SelectedIndexChanged(object sender, EventArgs e)
        {
            string currentID = ((QueueDetail)cboStoredQueues.SelectedItem).ID;
            

            Queue  currentQueue = queueList.Find(xPath => xPath.ID == currentID);
            if (currentQueue != null)
            {
                txtServer.Text = currentQueue.Server;
                txtQueue.Text = currentQueue.QueueName;
                txtUser.Text = currentQueue.User;
                txtPwd.Text = currentQueue.Password;
            }
        }
      

       
    }
}
